package com.android.jingweiapp.fragment.topic;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.GetKeywordInSpecialXMLPhase;
import com.android.jingweiapp.XMLPhase.GetKeywordInTopicPointXMLPhase;
import com.android.jingweiapp.XMLPhase.GetSpecialByKeywordXMLPhase;
import com.android.jingweiapp.XMLPhase.GetTopicPointByKeywordXMLPhase;
import com.android.jingweiapp.XMLPhase.TopicPointXMLPhase;
import com.android.jingweiapp.activity.SearchActivity;
import com.android.jingweiapp.activity.TopicSecondActivity;
import com.android.jingweiapp.adapter.HotWordAdapter;
import com.android.jingweiapp.adapter.TopicAdapter;
import com.android.jingweiapp.bean.HotWord;
import com.android.jingweiapp.bean.TopicBean;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.google.gson.Gson;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 专题聚焦
 */
public class TopicPointFragment extends Fragment {

    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.btn_search)
    TextView btnSearch;
    @Bind(R.id.list)
    ListView list;
    @Bind(R.id.keyWordView)
    RecyclerView keyWordView;

    private ArrayList<TopicBean.DataEntity> topicBeans;
    private TopicAdapter topicAdapter;
    private HotWord hotWord;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_topic2, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }
    /**
     * 获取经信专栏的关键字
     */


    class KeywordAsyncTask extends AsyncTask<Void,Void,String>{

        @Override
        protected String doInBackground(Void... params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetKeywordInTopicPointXMLPhase.createParam(getActivity()),
                    new GetKeywordInTopicPointXMLPhase());
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            createKeyword(s);
        }
    }

    private void createKeyword(String result) {
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");

        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("无更多数据");

            return;
        }
        Gson gson = new Gson();
        hotWord = gson.fromJson(result, HotWord.class);
        HotWordAdapter hotWordAdapter = new HotWordAdapter(getActivity(), hotWord.getData());
        keyWordView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        keyWordView.setAdapter(hotWordAdapter);
        hotWordAdapter.setOnItemClickListener(new HotWordAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, Parcelable data) {

                new SearchByKeywordAsyncTask().execute(((HotWord.DataEntity) view.getTag()).getContent());
            }
        });
    }


    class SearchByKeywordAsyncTask extends  AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.postWithContent(
                    Contacts.BASE_URL,
                    GetTopicPointByKeywordXMLPhase.createParam(getActivity(), params[0]),
                    new GetTopicPointByKeywordXMLPhase()
            );
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            dealData2(s);
        }
    }

    private void dealData2(String str) {
        if (TextUtils.isEmpty(str)) {
            MyToast.getInstance().show("出错了，请确认网络正常");
            return;
        }
        if(str.equals("nodata")){
            MyToast.getInstance().show("没有数据");
            return;
        }
        Gson gson = new Gson();
        TopicBean topicBean = gson.fromJson(str, TopicBean.class);
        if(topicBeans!=null){topicBeans.clear();}
        topicBeans.addAll(topicBean.getData());
        topicAdapter.notifyDataSetChanged();

    }


    private void init() {
        /**
         * 专题聚焦点击进入搜索界面。flag=7
         */
        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                    Intent intent = new Intent(getActivity(), SearchActivity.class);
                    intent.putExtra(Contacts.KEY.KEY_TYPE, Contacts.SEARCH_TYPE.Topic_Point);
                    startActivity(intent);
                }
            }
        });
        hotWord=new HotWord();
        topicBeans = new ArrayList<>();
        topicAdapter = new TopicAdapter(topicBeans, getActivity());
        list.setAdapter(topicAdapter);
        list.setOnItemClickListener(new MyOnItemClickListener());

        new MyAsyncTask().execute();
        new KeywordAsyncTask().execute();
    }

    public void onResume() {
        super.onResume();
        etSearch.clearFocus();
    }

    private void dealData(String str) {
        if (TextUtils.isEmpty(str)) {
            MyToast.getInstance().show("出错了，请确认网络正常");
            return;
        }
        Gson gson = new Gson();
        TopicBean topicBean = gson.fromJson(str, TopicBean.class);
        topicBeans.addAll(topicBean.getData());
        topicAdapter.notifyDataSetChanged();

    }

    class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(new Intent(getActivity(), TopicSecondActivity.class)
                    .putExtra(Contacts.KEY.KEY_OBJECT, topicBeans.get(position))
                    .putExtra(Contacts.KEY.KEY_TYPE, 1));
        }
    }

    class MyAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    TopicPointXMLPhase.createParam(getActivity()),
                    new TopicPointXMLPhase());
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            dealData(s);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
